package com.yztc.xiami_app.ui.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yztc.xiami_app.R;
import com.yztc.xiami_app.adapter.shopcart.ShopCartAdapter;
import com.yztc.xiami_app.bean.shopcart.ShopCart;
import com.yztc.xiami_app.constant.OtherConstant;
import com.yztc.xiami_app.ui.activity.order.OrderActivity;
import com.yztc.xiami_app.ui.shopcart.interfaces.ICheckChangeListener;
import com.yztc.xiami_app.ui.shopcart.presenter.IShopCartPresenter;
import com.yztc.xiami_app.ui.shopcart.presenter.ShopCartPresenterImpl;
import com.yztc.xiami_app.ui.shopcart.view.IShopCartView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobObject;

/**
 * A simple {@link Fragment} subclass.
 * <p>
 * "购物车"Fragment,
 */
public class ShopCartFragment extends Fragment implements IShopCartView,ICheckChangeListener {


    @BindView(R.id.shop_cart_rv)
    RecyclerView shopCartRv; //展示商品信息的RecyclerView
    @BindView(R.id.check_all_cb)
    CheckBox checkAllCb; //商品全选
    @BindView(R.id.total_price_tv)
    TextView totalPriceTv; //商品总价
    @BindView(R.id.count_btn)
    Button countBtn; //去结算
    @BindView(R.id.editableTv)
    TextView editableTv; //编辑，点击后变成“完成”
    @BindView(R.id.delete_goods_iv)
    ImageView deleteGoodsIv; //删除选中商品


    private Context mContext;
    private List<ShopCart> mList; //购物车的数据源
    private ShopCartAdapter mShopCartAdapter; //适配器
    private IShopCartPresenter mPresenter;
    private boolean flag; //是否显示商品数量的标识,如果为false，则表示不显示，如果为true，表示显示
    private int totalPrice; //商品的总价
    private List<ShopCart> mDeleteList = new ArrayList<>(); //将要删除的List集合
    private boolean isCheckAll; //是否全选

    public ShopCartFragment() {
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shop_cart, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);


        initShopCartRecyclerView();
        loadShopCartData();
    }


    //从Bmob获取购物车的数据
    private void loadShopCartData() {
        mPresenter = new ShopCartPresenterImpl(this);
        //获取购物车的数据
        mPresenter.getShopCart();
    }

    //初始化购物车的RecyclerView
    private void initShopCartRecyclerView() {
        mList = new ArrayList<>();
        mShopCartAdapter = new ShopCartAdapter(mContext, mList,this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, OrientationHelper.VERTICAL, false);
        shopCartRv.setAdapter(mShopCartAdapter);
        shopCartRv.setLayoutManager(layoutManager);
    }

    @OnClick({R.id.editableTv, R.id.delete_goods_iv, R.id.check_all_cb,R.id.count_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.editableTv:
                //ToolBar中的“编辑”的点击，点击后，变成完成
                flag = !flag; //重新设置是否显示数量的View的状态
                editableTv.setText(flag ? "完成" : "编辑");
                mShopCartAdapter.setisShowPM(flag);
                break;
            case R.id.delete_goods_iv:
                //删除选中
                deleteSelectedGoods();
                break;
            case R.id.check_all_cb:
                //全选
                selectAll();
                break;
            case R.id.count_btn:
                //去结算,跳转到订单页面
                List<ShopCart> goodsToOrderList = new ArrayList<>(); //传递到订单界面的List
                for (ShopCart shopCart:mList){
                    if(shopCart.getStatus()){
                        goodsToOrderList.add(shopCart); //把选中的商品添加到集合
                    }
                }
                //把集合转化成数组
                Intent intent = new Intent(mContext, OrderActivity.class);
                //把传递的数据强转为Serializable类型
                intent.putExtra(OtherConstant.KEY_GOODS_TO_ORDER,(Serializable) goodsToOrderList);
                startActivity(intent);
                break;
        }
    }

    //全选
    private void selectAll() {
        isCheckAll = !isCheckAll;
        for (int i = 0; i < mList.size(); i++) {
            ShopCart shopCart = mList.get(i);
            shopCart.setStatus(isCheckAll); //设置为全选状态，或者全部为选中状态
        }
        mShopCartAdapter.notifyDataSetChanged();
    }

    //删除选中
    private void deleteSelectedGoods() {
        List<BmobObject> cartList = new ArrayList<BmobObject>(); //Bmob中要删除的商品的List的集合
        for (int i = 0; i < mList.size(); i++) {
            ShopCart shopCart = mList.get(i);
            boolean status = shopCart.getStatus();
            if (status) {
                //把选中的商品添加到删除列表
                mDeleteList.add(shopCart);
                //把选中的商品添加到Bmob中的删除列表
                cartList.add(shopCart);
            }
        }
        mPresenter.deleteGoods(cartList); //从Bomb云的数据库中删除选中的商品
        //是否删除成功
        boolean isSuccess = mList.removeAll(mDeleteList);//删除选中的商品
        if (isSuccess) {
            mShopCartAdapter.notifyDataSetChanged();
            //清除总价
            totalPriceTv.setText("");
        }
    }


    //获取数据库中的购物车的数据
    @Override
    public void getShopCartData(List<ShopCart> shopCartList) {
        mList.addAll(shopCartList);
        mShopCartAdapter.notifyDataSetChanged();
        for (ShopCart shopCart : shopCartList) {
            int price = shopCart.getPrice();
            totalPrice += price;
        }
        //设置商品的总价
        totalPriceTv.setText("¥ " + totalPrice);
    }

    //显示删除选中的商品是否成功
    @Override
    public void showDeleteGoodsResult(boolean isSuccess) {
        if(isSuccess){
            Toast.makeText(mContext, "删除商品成功", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(mContext, "删除商品失败", Toast.LENGTH_SHORT).show();
        }
    }

    //动态设置商品的总价
    @Override
    public void setTotalPrice(int totalPrice) {
        totalPriceTv.setText("¥ "+totalPrice);
    }
}
